<?php

namespace app\api\controller;


use app\admin\model\CashcardUser;
use app\admin\model\ShopCate;
use app\admin\model\ShopSettle;
use app\admin\model\ShopStore;
use app\admin\model\UserBase;
use app\admin\model\UserOrder;
use app\admin\service\CurlService;
use app\admin\service\Hnnx;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Log;

class Store extends Api
{

    /**
     * @title 店铺页面
     * @return mixed
     * @author FashionJune
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * @title 商家入驻页面
     * @return mixed
     * @author FashionJune
     */
    public function settle()
    {
        return $this->fetch('', [
            'banner' => sysconfig('site', 'site_join_banner')
        ]);
    }

    /**
     * @title 店铺详情页面
     * @return mixed
     * @author FashionJune
     */
    public function detail()
    {
        return $this->fetch();
    }

    /**
     * @title 店铺搜索页面
     * @return mixed
     * @author FashionJune
     */
    public function search()
    {
        return $this->fetch();
    }

    /**
     * @title 搜索历史
     * @author FashionJune
     */
    public function searchHistory()
    {
        return array_slice(cookie('search_history'), -10, 10);
    }

    /**
     * @title 店铺搜索结果页面
     * @return mixed
     * @author FashionJune
     */
    public function searchResult()
    {
        return $this->fetch('search_result');
    }

    /**
     * @title 店铺支付页面
     * @return mixed
     * @author FashionJune
     */
    public function pay()
    {
        $prepay_cache_name = 'AuthCode' . $this->user['user_id'];
        $code = input('code');
        //预支付前需跳转金燕e付规定地址
        if (!cookie($prepay_cache_name) && !$code) {//未存有AuthCode字段，需要跳转
            $jump_url = config('hnnx.AuthUrl') . $this->request->url(true);
//            dd($jump_url);
            $this->redirect($jump_url);
        } elseif($code) {
            cookie($prepay_cache_name, $code, 30);
            Cookie::save();//没有这一步无法在exit后持续保存cookie
        }
        $store_id = input('m');
        $store_info = ShopStore::where('id', $store_id)->find();
        return $this->fetch('', [
            'store_info' => $store_info
        ]);
    }

    /**
     * @title 我的店铺页面
     * @return mixed
     * @author FashionJune
     */
    public function my()
    {
        $type = input('type', 0);
        if ($type == 0) {
            return $this->fetch();
        } else {
            return $this->fetch('info-my');
        }
    }


    /**
     * @title 店铺分类列表
     * @author FashionJune
     */
    public function getCateList()
    {
        $map = [
            ['status', '=', 1]
        ];
        $list = ShopCate::where($map)->order('sort', 'desc')->select();
        $count = ShopCate::where($map)->count();
        api_list_return($count, $list);
    }


    /**
     * @title 获取店铺列表
     * @author FashionJune
     */
    public function getStoreList()
    {
        $where = 'status = 1 AND delete_time is null ';
        $cate_id = input('cate_id');
        $key_word = input('key_word');
        $lat = input('lat');
        $lng = input('lng');
//        $max_distance = input('distance');
        $cate_id && ($where .= 'AND cate_id = ' . $cate_id);
        $key_word && ($where .= 'AND title like "%' . $key_word . '%"'); /*&& $this->addSearchHistory($key_word)*/
        $start = ($this->page - 1) * $this->per;
        $sql = get_distance_sql($lat, $lng, $start, $this->per, $where);
//        Log::write($sql);
        $stores = Db::query($sql);
        $count = ShopStore::where($where)->count();
        $card_package = [
            'cate' => CashcardUser::init()->getUserPackage($this->user['user_id'])
        ];
        if (in_array('', $card_package)) {
            $ex_data['cashcard_available'] = true;
        } else {
            $ex_data['cashcard_available'] = false;
            foreach ($stores as &$store) {
                $store['cashcard_available'] = in_array($store['cate_id'], $card_package);
            }
        }
        api_list_return($stores, $count, $ex_data ?? []);
    }

    /**
     * @title 添加搜索记录
     * @param $key_word
     * @author FashionJune
     */
    public function addSearchHistory($key_word)
    {
        $list = str2arr(cookie('search_history'));
        array_push($list, $key_word);
        (count($list) > 10) && array_shift($list);
        cookie('search_history', arr2str($list));
    }

    /**
     * @title 获取店铺详情
     * @author FashionJune
     */
    public function storeDetail()
    {
        api_success(ShopStore::with('goods')->find(input('store_id')));
    }

    /**
     * @title 商家入驻提交
     * @author FashionJune
     */
    public function settleSubmit()
    {
        $map = [
            'user_id' => $this->user['user_id'],
            'status' => 0
        ];
        (ShopSettle::init()->where($map)->find()) && api_error('请耐心等待上次审核结果');
        $insert_data = [
            'user_id' => $this->user['user_id'],
            'shop_name' => input('name'),
            'shop_address' => input('address'),
            'shop_keeper' => input('keeper'),
            'shop_mobile' => input('mobile'),
        ];
        $rule = [
            'shop_name|店铺名称' => 'require',
            'shop_address|店铺地址' => 'require',
            'shop_keeper|联系人' => 'require',
            'shop_mobile|联系方式' => 'require',
        ];
        $this->validate($insert_data, $rule);
        ShopSettle::init()->save($insert_data) && api_success('提交成功') || api_error('提交失败，请检查数据');
    }

    /**
     * @title 查询可用卡片
     * @author FashionJune
     */
    public function checkCashcard()
    {
        $store_id = input('store_id');
        $price = input('price', 999999);
        $store_cate = ShopStore::where('id', $store_id)->value('cate_id');
        $map_cashcard = [
            ['status', '=', 0],
            ['min_order_price', '<=', $price],
            ['to_user', '=', $this->user['user_id']]
        ];
//        $list = CashcardUser::where($map_cashcard)->order('cashcard_price', 'desc')->select();
        $list = Db::view('cashcard_user', 'id,cate_id,create_time,used_time,expire_time,status')
            ->view('cashcard_cate', 'min_order_price,cashcard_price,tips,attention,title,card_type,related_cate', 'cashcard_user.cate_id=cashcard_cate.id')
            ->where($map_cashcard)->where(function ($query) use ($store_cate) {
                $query->where('cashcard_user.related_cate', '=', $store_cate)->whereOr('cashcard_user.related_cate', '=', '');
            })->order('cashcard_price', 'desc')->select()->each(function ($item) {
                $item['create_at'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['used_at'] = date('Y-m-d H:i:s', $item['used_time']);
                $item['expire_at'] = date('Y-m-d H:i:s', $item['expire_time']);
                if ($item['card_type'] == 2) {
                    $item['cate_name'] = ShopCate::where('id', $item['related_cate'])->cache()->value('title');
                } else {
                    $item['cate_name'] = '通用券';
                }
                return $item;
            });
        api_list_return($list);
//        $map_disabled = [
//            ['to_user', '=', $this->user['user_id']],
//            ['related_cate', '>', 0]
//        ];
//        $list2 = CashcardUser::where($map_disabled)->where(function ($query) use ($store_cate, $price) {
//            $query->where('related_cate', '<>', $store_cate)->whereOr('status', -1)
//                ->whereOr('expire_time', '<', time())->whereOr('min_order_price', '>', $price);
//        })->select();
//        api_success([
//            'list1' => $list1,
//            'count1' => $count1,
//            'list2' => $list2,
//            'count2' => $count2,
//        ]);
    }

    /**
     * @title 支付订单
     * @throws \Exception
     * @author FashionJune
     */
    public function submitPay()
    {
        $prepay_cache_name = 'AuthCode' . $this->user['user_id'];
//        api_error($prepay_cache_name);
        $cookie_code = cookie($prepay_cache_name);
        if (!$cookie_code) {
            api_error('支付令牌过期，请刷新后重试');
        }
//        api_error($cookie_code);
//        api_error($this->client);
        $store_id = input('store_id/d');
        (!$store_id) && api_error('缺少支付商家信息');
        $price = input('price/f', 0);
        ($price <= 0) && api_error('请输入正确的金额');
        $card_id = input('card_id');
        $store_cate = ShopStore::where(['id' => $store_id])->value('cate_id') ?? api_error('未找到店铺');
        $card_info = [];
        if ($card_id) {//使用代金券
            //检查该代金券是否可用
            $re = CashcardUser::init()->isAvailable($card_id, $store_cate, $this->user['user_id']);
            (!$re['status']) && api_error($re['msg']);
            $card_info = $re['data'];
        }
//        api_error($this->PayTypCd);
        //预支付
        $prepay_data = [
            'money' => $price-($card_info['cate']['cashcard_price'] ?? 0),
            'SubMerchantId' => ShopStore::init()->getValueByKey('merchant_id', $store_id),
//            'SubMerchantId' => 'AA1637511118050',
            'PayTypCd' => $this->PayTypCd,
            'OrderTitle' => ShopStore::init()->getValueByKey('title', $store_id),
            'OperatorId' => 'user_' . $this->user['user_id'],
            'MerSeqNbr' => UserOrder::init()->createOrderSn($store_id, $this->user['user_id']),
        ];
        $prepay_data['AuthCode'] = $cookie_code;
        if ($this->client == 'alipay') {
//            cookie($prepay_cache_name, null);
//            Cookie::save();
//            $prepay_data['AuthCode'] = '2fe0f9bc1dde4fc3a3bd06f673aaQX81';

        } else {
//            $prepay_data['AuthCode'] = '2fe0f9bc1dde4fc3a3bd06f673aaQX81';
//            api_error($prepay_data['AuthCode']);
        }
//        api_error($prepay_data['AuthCode']);

        $result =  Hnnx::instance()->prepay($prepay_data);
        Log::write(json_encode($result));
//        trace(json_encode($result));
        try {
            if ($result['code'] !== 1) {//未成功
                api_error($result['msg']);
            }
        } catch (\Exception $e) {
            api_error($e->getMessage());
        }

        //成功后返回结果，跳转支付
        if ($card_id) { //销毁代金券
            CashcardUser::init()->destroyCard($card_id);
        }
        //生成订单
        $pay_data = $result['data'] ?? [];
        $pay_data['pay_type'] = ($this->client == 'wechat') ? 2: 1;
        UserOrder::init()->createOrderByUser((int)$store_id, $this->user['user_id'], $price, $pay_data, $card_info);
        api_success($result['data'], $result['msg']);
    }


    /**
     * @title 预支付
     * @author FashionJune
     * @return array|void
     */
    public function prePay()
    {
        //构造预支付数据
        $prepay_data = cache('prepay_data_' . $this->user['user_id']);
        $prepay_data['AuthCode'] = cache('AuthCode') ?? input('code');
        $result =  Hnnx::instance()->prepay($prepay_data);
        if ($result['code'] !== 1) {//未成功
            return error($result['message']);
        }
        return success($result['data'], $result['message']);
    }


    /**
     * @title 获取我的店铺列表
     * @author FashionJune
     */
    public function getMyStore()
    {
        $store_list = UserBase::where('id', $this->user['user_id'])->value('bind_store');
        $list = ShopStore::whereIn('id', str2arr($store_list))->select();
        api_list_return($list);
    }

}
